package com.suxin.sms;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Tang
 * @classname SmsService
 * @description [  ]
 * @date 2021/3/10 14:25
 */
public class SmsService {

    private static final BlockingQueue<SmsMessage> blockQueue = new ArrayBlockingQueue<>(512);

    private static final ExecutorService executor = Executors.newFixedThreadPool(5);

    private static AtomicBoolean RUNNING = new AtomicBoolean(false);

    public void send(SmsMessage smsMessage) throws Exception{
        blockQueue.put(smsMessage);
        if (RUNNING.compareAndSet(false, true)) {
            executor.execute(() -> {
                try {
                    while (RUNNING.get()) {
                        if (blockQueue.isEmpty()) {
                            TimeUnit.SECONDS.sleep(1);
                        }
                        SmsMessage message = blockQueue.take();
                        doSend(smsMessage);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private void doSend(SmsMessage smsMessage) {
        System.out.println("send message...." + smsMessage);
    }

}